package com.hcz.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.hcz.entity.User;
import com.hcz.util.DbHelp;
import com.hcz.util.ResultSetPackge;

public class UserDao {

	DbHelp<User> db = new DbHelp<User>();
	
	/**
	 * 查找所有用户
	 * @return
	 * 
	 */
	public List<User>selectForAll(){
		String sql = "select id ,name,password,money,state from t_account";
		return db.exeSelectForList(sql,  new PackgeUser());
	}
	/**
	 * 根据用户名和密码查找用户
	 * @param name
	 * @param pwd
	 * @return
	 */
	public User selectByNameAndPwd(String name,String pwd){
		String sql = "select id ,name,password,money,state from t_account where name = ? and password = ?";
		return db.exeSelectForObject(sql, new PackgeUser(), name,pwd);
	}
	/**
	 * 根据用户名查找用户
	 * @param name
	 * @return
	 */
	public User selectByName(String name){
		String sql = "select id ,name,password,money,state from t_account where name = ?";
		return db.exeSelectForObject(sql, new PackgeUser(), name);
		
	}
	/**
	 * 在线开户
	 * @param name
	 * @param pwd
	 * @return
	 */
	public int createAccount(User user){
		String sql = "insert into t_account(name,password,money,state)values(?,?,?,?)";
		return db.executeUpdateSql(sql, user.getName(),user.getPassword(),user.getMoney(),user.isState());
		
	} //开户成功，跳转登录页面
	
	/**
	 * 修改用户金额
	 * @param user
	 * @return
	 */
	public int updateMoney(User user ){
		String sql = "update t_account set money = ? where id = ?";
		return db.executeUpdateSql(sql, user.getMoney(),user.getId());
		
	}
	/**
	 * 修改用户密码：
	 * @param user
	 * @return
	 */
	public int updatePwd(User user){
		String sql="update t_account set password=? where id = ?";
		return db.executeUpdateSql(sql, user.getPassword(),user.getId());
		
	}
	/**
	 * 根据用户名修改用户状态
	 * @param user
	 * @return
	 */
	public int updateState(User user){
		String sql="update t_account set state=? where name=?";
		return db.executeUpdateSql(sql, user.isState(),user.getName());
	}
	private class PackgeUser implements ResultSetPackge<User>{
		public User packgeResultSet(ResultSet rs) throws SQLException {
			User user = new User();
			user.setId(rs.getInt("id"));
			user.setName(rs.getString("name"));
			user.setPassword(rs.getString("password"));
			user.setMoney(rs.getFloat("money"));
			user.setState(rs.getBoolean("state"));
			return user;
		}
		
		
	}
}
